package org.yangspring.samples.mvc.daoOracle;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.yangspring.samples.mvc.domainOracle.DBAUsers;
import org.yangspring.samples.mvc.listeners.ContentEvent;

import java.util.List;

/**
 * Created by whyang on 2017/06/22.
 */

@Repository
public class DBAUsersDAOImpl implements DBAUsersDAO {

    private static final Logger logger = LoggerFactory.getLogger(DBAUsersDAO.class);

    @Autowired
    @Qualifier("hibernate5AnnotatedSessionFactoryOracle")
    private SessionFactory sessionFactory;
    /*public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }*/

    /****
     * Way 1 for use Autowired Annotation
     * Annotate Field of one Class
     * Annotate a method of one Class
     * Annotate constructor method of one Class
     * **/
    @Autowired
    private ApplicationContext appCntx;

    public List<DBAUsers> listUser(){
//        Session session = this.sessionFactory.getCurrentSession();
        Session session = this.sessionFactory.openSession();
        TransactionSynchronizationManager.bindResource(this.sessionFactory, session);

        this.appCntx.publishEvent(new ContentEvent("Now FrankieYang 's Blog Updating from DBAUsersDAOImpl\n"));
        this.appCntx.publishEvent(new ApplicationEvent("Now WHYANG 's Blog Updating from DBAUsersDAOImpl\n") {
            @Override
            public Object getSource() {
                return super.getSource();
            }
        });

        List<DBAUsers> userList = session.createQuery("from DBAUsers").list();

        for(DBAUsers t : userList){
            logger.info("DBAUsers List::" + t);
        }
        return userList;
    }

}
